/**
 * 
 */
package com.exject.android.socialphonebook.view;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TableRow.LayoutParams;

import com.exject.android.socialphonebook.R;
import com.exject.android.socialphonebook.data.Address;
import com.exject.android.socialphonebook.data.Contact;
import com.exject.android.socialphonebook.data.EMailAddress;
import com.exject.android.socialphonebook.data.Note;
import com.exject.android.socialphonebook.data.Organization;
import com.exject.android.socialphonebook.data.PhoneNumber;
import com.exject.android.socialphonebook.logutil.LogUtil;
import com.exject.android.socialphonebook.util.RetrieveContactHelper;

/**
 * @author Benjamin Nagel <benjamin.nagel@stud.fh-dortmund.de>
 */
public class DisplayContactInformationActivity extends Activity {
    private static final int TELEPHONE_CONTEXT_MENU_CALL = 100;
    private static final int TELEPHONE_CONTEXT_MENU_WRITE_SMS = 101;
    private static final int TELEPHONE_CONTEXT_MENU_WRITE_MMS = 102;
    private static final int TELEPHONE_CONTEXT_MENU_CLOSE = 109;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.display_contact_information);
        
        final long defaultValue = Long.MIN_VALUE;
        final long contactId = this.getIntent().getExtras()
            .getLong("contactId", defaultValue);
        if(contactId != defaultValue) {
            final RetrieveContactHelper retrieveContactHelper = new RetrieveContactHelper(
                    this.getContentResolver());
            final Contact contact = retrieveContactHelper.getContactById(contactId);
            
            if (contact != null) {
                if (contact.getName() != null) {
                    final TextView contactName = (TextView) this
                            .findViewById(R.id.displayContactContactName);
                    contactName.setText("" + contact.getName());
                }
                
                final TableLayout contactInformationsTableLayout = (TableLayout) this
                        .findViewById(R.id.displayContactTable);
                
                this.showPhoneNumbers(contact, contactInformationsTableLayout);
                this.showAddresses(contact, contactInformationsTableLayout);
                this.showEMailAddresses(contact, contactInformationsTableLayout);
                this.showOrganizations(contact, contactInformationsTableLayout);
                this.showNotes(contact, contactInformationsTableLayout);
            } else {
                Toast.makeText(this.getApplicationContext(),
                        R.string.errorToastCantFindContact, Toast.LENGTH_SHORT)
                        .show();
                Log.e("AtracuraPhonebookError",
                        "I found now contact... strange. ID: " + contactId);
            }
        } else {
            //TODO: Error Message, no contact selected
        }
    }
    
    /**
     * @param contact
     * @param table
     */
    private void showNotes(final Contact contact, final TableLayout table) {
        if (contact.getNotes() != null) {
            this.createHeaderRow(table,
                    R.string.displayContactRowTitleOrganization);
            
            for (int i = 0; i < contact.getNotes().size(); i++) {
                final Note note = contact.getNotes().get(i);
                
                final TableRow noteRow = new TableRow(table.getContext());
                table.addView(noteRow);
                
                this.createEmptyTextView(noteRow);
                this.createEmptyTextView(noteRow);
                
                this.createTextView(note.getNote(), noteRow);
            }
        }
    }
    
    /**
     * @param contact
     * @param table
     */
    private void showOrganizations(final Contact contact,
            final TableLayout table) {
        if (contact.getOrganizations() != null) {
            this.createHeaderRow(table,
                    R.string.displayContactRowTitleOrganization);
            
            for (int i = 0; i < contact.getOrganizations().size(); i++) {
                final Organization organization = contact.getOrganizations()
                        .get(i);
                
                final TableRow organizationRow = new TableRow(table
                        .getContext());
                table.addView(organizationRow);
                
                this.createEmptyTextView(organizationRow);
                
                this
                        .createTextView(organization.getPosition(),
                                organizationRow);
                this.createTextView(organization.getCompanyName(),
                        organizationRow);
            }
        }
    }
    
    private void createEmptyTextView(final TableRow row) {
        final TextView emptyCell = new TextView(row.getContext());
        row.addView(emptyCell);
    }
    
    private void createTextView(final String text, final TableRow row) {
        final TextView textView = new TextView(row.getContext());
        textView.setText(text);
        textView.setPadding(5, 0, 5, 0);
        row.setPadding(5, 0, 5, 0);
        row.addView(textView);
    }
    
    private void createTextView(final int textId, final TableRow row) {
        final TextView textView = new TextView(row.getContext());
        textView.setText(textId);
        textView.setPadding(5, 0, 5, 0);
        row.setPadding(5, 0, 5, 0);
        row.addView(textView);
    }
    
    private void createHeaderRow(final TableLayout table, final int titleId) {
        final TableRow organizationHeaderRow = new TableRow(table.getContext());
        table.addView(organizationHeaderRow);
        final TextView header = new TextView(organizationHeaderRow.getContext());
        final LayoutParams rowLayout = new LayoutParams();
        rowLayout.span = 3;
        header.setText(titleId);
        organizationHeaderRow.addView(header, rowLayout);
    }
    
    private void showEMailAddresses(final Contact contact,
            final TableLayout table) {
        if (contact.getEMailAddresses() != null) {
            this.createHeaderRow(table,
                    R.string.displayContactRowTitleOrganization);
            
            for (int i = 0; i < contact.getEMailAddresses().size(); i++) {
                final EMailAddress eMailAddress = contact.getEMailAddresses()
                        .get(i);
                
                final TableRow eMailRow = new TableRow(table.getContext());
                table.addView(eMailRow);
                
                this.createEmptyTextView(eMailRow);
                
                this.createTextView(eMailAddress.getType().getType(), eMailRow);
                this.createTextView(eMailAddress.geteMailAddress(), eMailRow);
            }
        }
    }
    
    private void showAddresses(final Contact contact, final TableLayout table) {
        if (contact.getAddresses() != null) {
            this.createHeaderRow(table,
                    R.string.displayContactRowTitleOrganization);
            
            for (int i = 0; i < contact.getAddresses().size(); i++) {
                final Address address = contact.getAddresses().get(i);
                
                final TableRow addressRow = new TableRow(table.getContext());
                table.addView(addressRow);
                
                this.createEmptyTextView(addressRow);
                
                this.createTextView(address.getType().getType(), addressRow);
                this.createTextView(address.toString(), addressRow);
            }
        }
    }
    
    private void showPhoneNumbers(final Contact contact, final TableLayout table) {
        if (contact.getPhoneNumbers() != null) {
            this.createHeaderRow(table,
                    R.string.displayContactRowTitleOrganization);
            
            for (int i = 0; i < contact.getPhoneNumbers().size(); i++) {
                final PhoneNumber number = contact.getPhoneNumbers().get(i);
                final TableRow telephonRow = new TableRow(table.getContext());
                table.addView(telephonRow);
                
                this.createTextView(R.string.telephoneTypeCall, telephonRow);
                this.createTextView(number.getType().getType(), telephonRow);
                this
                        .createTextViewToCall(number.getMobileNumber(),
                                telephonRow);
                
                // TODO: ADD function to call / send sms / MMS and so on
            }
        }
    }
    
    /**
     * @param mobileNumber
     * @param telephonRow
     */
    private void createTextViewToCall(final String mobileNumber,
            final TableRow row) {
        final TextView textView = new TextView(row.getContext());
        textView.setText(mobileNumber);
        textView.setPadding(5, 0, 5, 0);
        row.setPadding(5, 0, 5, 0);
        row.addView(textView);
        
        /*
         * Intent sendIntent = new Intent(Intent.ACTION_VIEW);
         * sendIntent.putExtra("sms_body", "Content of the SMS goes here...");
         * sendIntent.setType("vnd.android-dir/mms-sms");
         * startActivity(sendIntent);
         */

        textView.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(final View v) {
                DisplayContactInformationActivity.this.makeCall(mobileNumber);
            }
            
        });
        this.registerForContextMenu(textView);
    }
    
    @Override
    public void onCreateContextMenu(final ContextMenu menu, final View v,
            final ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        // TODO: Text String ID's
        menu.add(0, DisplayContactInformationActivity.TELEPHONE_CONTEXT_MENU_CALL,
                0, "Call").setOnMenuItemClickListener(
                new OnMenuItemClickListener() {
                    
                    @Override
                    public boolean onMenuItemClick(final MenuItem item) {
                        final TextView telephoneNumberView = (TextView) v;
                        DisplayContactInformationActivity.this
                                .makeCall(telephoneNumberView.getText()
                                        .toString());
                        return true;
                    }
                });
        menu
                .add(
                        0,
                        DisplayContactInformationActivity.TELEPHONE_CONTEXT_MENU_WRITE_SMS,
                        1, "Write SMS").setOnMenuItemClickListener(
                        new OnMenuItemClickListener() {
                            
                            @Override
                            public boolean onMenuItemClick(final MenuItem item) {
                                final TextView telephoneNumberView = (TextView) v;
                                final String telephoneNumber = telephoneNumberView
                                        .getText().toString();
                                
                                final Intent intent = new Intent(
                                        DisplayContactInformationActivity.this,
                                        SendSMSActivity.class);
                                intent.putExtra("telephonNumber",
                                        telephoneNumber);
                                DisplayContactInformationActivity.this
                                        .startActivity(intent);
                                return true;
                            }
                        });
        menu
                .add(
                        0,
                        DisplayContactInformationActivity.TELEPHONE_CONTEXT_MENU_WRITE_MMS,
                        2, "Write MMS").setOnMenuItemClickListener(
                        new OnMenuItemClickListener() {
                            
                            @Override
                            public boolean onMenuItemClick(final MenuItem item) {
                                // TODO: WRITE MMS
                                Toast.makeText(
                                        DisplayContactInformationActivity.this,
                                        "NOT YET IMPLEMENTED",
                                        Toast.LENGTH_LONG).show();
                                return true;
                            }
                        });
        menu.add(0,
                DisplayContactInformationActivity.TELEPHONE_CONTEXT_MENU_CLOSE, 0,
                "Delete").setOnMenuItemClickListener(
                new OnMenuItemClickListener() {
                    
                    @Override
                    public boolean onMenuItemClick(final MenuItem item) {
                        // TODO Auto-generated method stub
                        return true;
                    }
                });
    }
    
    private void makeCall(final String mobileNumber) {
        final Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel://"
                + mobileNumber.trim()));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // intent.setClassName(mApp, PhoneApp.getCallScreenClassName());
        DisplayContactInformationActivity.this.startActivity(intent);
    }
    
}
